﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

using PacketAnalyzer.Analyzer;

using PacketAnalyzer.Data;

namespace PacketAnalyzer
{
    public partial class MainForm : Form
    {
        DataTable dt = new DataTable();
        DataView dv = new DataView();

        List<String> packetList = new List<String>();

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            Initialize(dataGridViewResult);

            SetResultColumn( dt );

            dv = new DataView(dt, "순서 = 1" + " AND 블록카운트 = 1", "", DataViewRowState.CurrentRows);

            dataGridViewResult.DataSource = dv;

            dataGridViewResult.Columns["순서"].Visible = false;
            dataGridViewResult.Columns["블록카운트"].Visible = false;
        }

        private void buttonAnalyze_Click(object sender, EventArgs e)
        {

            string packets = richTextBoxPacket.Text;

            string[] tokens = packets.Split(new string[] { Environment.NewLine, "\n" }, StringSplitOptions.None);

            // Initialize
            dt.Rows.Clear();
            comboBoxDataCount.Items.Clear();
            packetList.Clear();

            Int16 count = 1;

            for (int i = 0; i < tokens.Length; i++)
            {

                string packet = tokens[i];

                List<PacketData> packetDataList = PacketDataFactory.Analyze(packet);

                if (packetDataList != null && packetDataList.Count > 0)
                {
                    packetList.Add(packet);

                    int blockCount = 1;

                    foreach (PacketData packetData in packetDataList)
                    {
                        foreach (string key in packetData.keyList)
                        {
                            object[] view = new object[4];

                            view[0] = count;
                            view[1] = blockCount;
                            view[2] = key;
                            view[3] = packetData.keyValuePair[key];

                            dt.Rows.Add(view);

                            Debug.WriteLine(key + " : " + packetData.keyValuePair[key]);                            
                        }

                        blockCount++;
                    }

                    count++;
                }                
            }            

            for (int j = 1; j < count; j++)
            {
                comboBoxDataCount.Items.Add((j).ToString());
            }

            if (comboBoxDataCount.Items.Count > 0)
                comboBoxDataCount.SelectedIndex = 0;

            if (comboBoxBlockCount.Items.Count > 0)
                comboBoxBlockCount.SelectedIndex = 0;
        }


        private static DataColumn MakeColumn(Type dataType, String name)
        {

            DataColumn col = new DataColumn();
            col.DataType = dataType;
            col.ColumnName = name;

            return col;
        }

        /// <summary>
        /// 분석 결과
        /// </summary>
        /// <param name="dt"></param>
        public static void SetResultColumn(DataTable dt)
        {
            // "종목코드", "이름", "상태", "매수(도)", "NAV", "Skewness", "주문최소수량", "주문최대수량", "최대체결수량", "현재가격", "주문수량", "체결수량"
            dt.Columns.Add(MakeColumn(System.Type.GetType("System.Int16"), "순서"));
            dt.Columns.Add(MakeColumn(System.Type.GetType("System.Int16"), "블록카운트"));
            dt.Columns.Add(MakeColumn(System.Type.GetType("System.String"), "필드"));
            dt.Columns.Add(MakeColumn(System.Type.GetType("System.String"), "값"));
            
            DataColumn[] key = new DataColumn[3];
            key[0] = dt.Columns[0];
            key[1] = dt.Columns[1];
            key[2] = dt.Columns[2];

            dt.PrimaryKey = key;
        }
        
        private void comboBoxDataCount_SelectedIndexChanged(object sender, EventArgs e)
        {
            int selectedIndex = comboBoxDataCount.SelectedIndex + 1;

            comboBoxBlockCount.Items.Clear();

            int blockCount = 1;
            foreach (DataRow dr in dt.Rows)
            {
                if ((Int16)dr["순서"] == selectedIndex && (Int16)dr["블록카운트"] > blockCount)
                {
                    blockCount = (Int16)dr["블록카운트"];
                }
            }

            for (int i = 1; i <= blockCount; i++)
            {
                comboBoxBlockCount.Items.Add(i);
            }

            labelTotal.Text = "(Total: " + blockCount + ")";

            dv = new DataView(dt, "순서 = " + selectedIndex + " AND 블록카운트 = 1", "", DataViewRowState.CurrentRows);
            dataGridViewResult.DataSource = dv;

            richTextBoxOriginalPacket.Text = packetList[selectedIndex - 1];
        }

        private void comboBoxBlockCount_SelectedIndexChanged(object sender, EventArgs e)
        {
            int selectedIndex = comboBoxDataCount.SelectedIndex + 1;
            int selectedBlockIndex = comboBoxBlockCount.SelectedIndex + 1;

            dv = new DataView(dt, "순서 = " + selectedIndex + " AND 블록카운트 = " + selectedBlockIndex, "", DataViewRowState.CurrentRows);
            dataGridViewResult.DataSource = dv;
        }






        /// <summary>
        /// 기본 DataGrid Setting 
        /// </summary>
        /// <param name="dataGridView"></param>
        /// <param name="columnName"></param>
        /// <param name="columnWidth"></param>
        private void Initialize(DataGridView dataGridView)
        {
            //dataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Olive;
            //dataGridView.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
            dataGridView.ColumnHeadersDefaultCellStyle.Font =
                new Font(dataGridView.Font, FontStyle.Bold);

            dataGridView.Name = "dataGridOrder";
            //dataGridView.AutoSizeRowsMode =
            //    DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;

            //dataGridView.AutoSizeColumnsMode =
            //    DataGridViewAutoSizeColumnsMode.Fill;

            dataGridView.ColumnHeadersBorderStyle =
                DataGridViewHeaderBorderStyle.Single;
            dataGridView.CellBorderStyle = DataGridViewCellBorderStyle.Single;
            //dataGridView.GridColor = Color.White;
            dataGridView.RowHeadersVisible = false;
            //dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            // 기본적으로 편집 기능을 제한한다.
            dataGridView.ReadOnly = true;

            dataGridView.DefaultCellStyle.WrapMode = DataGridViewTriState.NotSet;
            dataGridView.AllowUserToResizeColumns = true;

            dataGridView.CurrentCell = null;

            dataGridView.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            dataGridView.AllowUserToAddRows = false;
            //dataGridView.AllowUserToResizeColumns = false;
            dataGridView.AllowUserToResizeRows = false;

            dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            // Added
            //dataGridView.AutoGenerateColumns = false;
        }

        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            //dataGridViewResult.Height = this.Height - 399;

            panelLeft.Height = this.Height - 58;
            panelRight.Height = this.Height - 58;

            this.Width = 1171;
        }

        private void panelLeft_SizeChanged(object sender, EventArgs e)
        {
            richTextBoxPacket.Height = panelLeft.Height - 78;

            buttonAnalyze.Location = new Point(buttonAnalyze.Location.X, panelLeft.Height - 37);
        }

        private void panelRight_SizeChanged(object sender, EventArgs e)
        {
            dataGridViewResult.Height = panelRight.Height - 249;
        }
    }
}
